package com.example.firstjavamqtt.controller.mqtt_api;

import com.alibaba.fastjson.JSONObject;
import com.example.firstjavamqtt.service.log.DeviceLogService;
import com.example.firstjavamqtt.service.log.LedLogService;
import com.example.firstjavamqtt.common.result.Result;
import com.example.firstjavamqtt.consumer.MqttConsumer;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;

@RestController
@RequestMapping("/mqtt/led")
@Api(tags = "控制板载LED接口")
public class LedController {

    @Autowired
    private LedLogService ledLogService;

    @Autowired
    private DeviceLogService deviceLogService;

    @ApiOperation("控制led开关")
    @PostMapping(value = "/{topic}")
    public Result controlLed(HttpServletRequest request, @PathVariable String topic, @RequestBody HashMap data) {
        String string = JSONObject.toJSONString(data);
        //存led日志
        ledLogService.saveLedLog(string,request);
        //存设备日志
        deviceLogService.saveDeviceLog(string,request);
        //转发消息
        MqttConsumer.publish(topic, string);
        return Result.ok();
    }

    @ApiOperation("控制闪烁灯开关")
    @PostMapping(value = "/LedStream/{topic}")
    public Result controlStreamLed(HttpServletRequest request, @PathVariable String topic,  @RequestBody HashMap data) {
        String string = JSONObject.toJSONString(data);
        //存led日志
        ledLogService.saveLedLog(string,request);
        deviceLogService.saveDeviceLog(string,request);
        //转发消息
        MqttConsumer.publish(topic,string);
        return Result.ok();
    }

    @ApiOperation("控制闪烁灯速度")
    @PostMapping(value = "/LedStreamSpeed/{topic}")
    public Result controlStreamLedSpeed(HttpServletRequest request, @PathVariable String topic,  @RequestBody HashMap data) {
        String string = JSONObject.toJSONString(data);
        //存led日志
        ledLogService.saveLedLog(string,request);
        deviceLogService.saveDeviceLog(string,request);
        //转发消息
        MqttConsumer.publish(topic, string);
        return Result.ok();
    }

}
